package com.ithe.shopweb.component;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.ithe.shopweb.common.Constants;
import com.ithe.shopweb.exception.ServiceException;
import com.ithe.shopweb.pojo.Customer;
import com.ithe.shopweb.pojo.Manager;
import com.ithe.shopweb.serve.LoginServe;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 功能：
 * 日期： 2024/4/7 12:27
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginServe loginServe;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");

        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        if(StrUtil.isBlank(token)) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录！");
        }

        //  获取token中的userid
        String userid;
        try {
            userid = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException jwtDecodeException) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录！");
        }

        //  根据token中的userid查询数据库
        Customer customer = loginServe.searchCustomer(userid);
        Manager manager = loginServe.searchManage(userid);

        // 当customer和manager都为null时，抛出异常
        if(customer == null && manager == null) {
            throw new RuntimeException("用户不存在！");
        }

        //  验证token
        JWTVerifier jwtVerifier = null;
        if (customer != null) {
            jwtVerifier = JWT.require(Algorithm.HMAC256(customer.getPassword())).build();
        } else if (manager != null) {
            jwtVerifier = JWT.require(Algorithm.HMAC256(manager.getPassword())).build();
        }

        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录！");
        }

        return true;
    }
}
